package com.javatom.notes.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.javatom.notes.common.enums.HttpReponseCodeEnum;
import com.javatom.notes.common.model.R;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 通过流回去
 * @author: 曾维录
 * @time: 2019/7/30 15:37
 */
public class ResponseUtil {
    private ResponseUtil() {
        throw new IllegalStateException("Utility class");
    }
    /**
     * 通过流写到前端
     *
     * @param objectMapper 对象序列化
     * @param response
     * @param msg          返回信息
     * @param httpStatus   返回状态码
     * @throws IOException
     */
    public static void responseWriter(ObjectMapper objectMapper, HttpServletResponse response, String msg, int httpStatus) throws IOException {

        response.setStatus(httpStatus);

        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try (
                Writer writer = response.getWriter()
        ) {
            writer.write(objectMapper.writeValueAsString(
                    R.fail(HttpReponseCodeEnum.UNAUTHORIZED.getCode(), msg)));
            writer.flush();
        }
    }
}
